<template>
  <div class="all-wrap">
    <div class="all-title">轮播图管理</div>
    <div class="top-controllers" style="margin-bottom: 4px;">
      <el-input v-model="searchValue" clearable class="w-50 m-2" placeholder="请输入标题" />
      <el-button type="primary" @click="searchClick">搜索</el-button>
      <el-button type="primary" @click="addPicFn">新增</el-button>
    </div>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column type="index" width="50" />
      <el-table-column label="图片" width="150">
        <template #default="scope">
          <img :src="scope.row.url" style="width: 100%;">
        </template>
      </el-table-column>
      <el-table-column prop="title" label="title" width="150" />
      <el-table-column prop="target" label="跳转详情地址" width="250">
        <template #default="scope">
          {{ returnName(scope.row.target) }}
        </template>
      </el-table-column>
      <el-table-column prop="url" label="url" />
      <el-table-column label="排序" width="180">
        <template #default="scope">
          <el-input-number v-model="scope.row.short" :min="1" :max="1000" @change="handleChangeSort(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column prop="isShow" label="是否显示" width="100">
        <template #default="scope">
          <el-switch v-model="scope.row.isShow" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #989595"
            @change="switchChange(scope.row)" active-value="1" inactive-value="2" />
        </template>
      </el-table-column>
      <el-table-column label="Controllers">
        <template #default="scope">
          <el-button type="primary" size="small" @click="editData(scope.row)">修改</el-button>
          <el-popconfirm width="220" confirm-button-text="OK" cancel-button-text="No, Thanks" :icon="InfoFilled"
            icon-color="#626AEF" title="Are you sure to delete this?" @confirm="confirmEvent(scope.row)">
            <template #reference>
              <el-button>Delete</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <br />
    <el-pagination v-model:current-page="currentPage" :page-size="10" layout="total, prev, pager, next" :total="dataTotal"
      @current-change="handleCurrentChange" />
    <el-dialog v-model="dialogFormVisible" :title="dialogState" >
      <el-form :model="form" ref="ruleFormRef" label-width="100" :rules="rules">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="跳转详情页" prop="target">
          <el-select v-model="form.target" filterable placeholder="Select" style="width: 100%">
            <el-option v-for="item in haibaoList" :key="item.id" :label="item.title" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload ref="upload" class="upload-demo" action="/shopApi/upload" :limit="1" :on-exceed="handleExceed"
            :on-success="uploadSuccess" :before-remove="beforeRemove" v-model:file-list="fileList" :auto-upload="true">
            <template #trigger>
              <el-button type="primary">select file</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip text-red">
                限制上传一张，多上传会覆盖上一张
              </div>
              <div>{{ editDataUrl }}</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch v-model="form.isShow" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #989595"
            active-value="1" inactive-value="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel(ruleFormRef)">取消</el-button>
          <el-button type="primary" @click="submit(ruleFormRef)">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogAuth" title="修改权限">
      <el-select v-model="authArr" multiple placeholder="Select" style="width: 100%">
        <el-option v-for="item in authsOptions" :key="item.id" :label="item.authName" :value="item.id" />
      </el-select>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="submitEdit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, onBeforeMount } from 'vue';
import { ElMessage, FormInstance } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import { getBannerPic, deletePic, addBannerData, deletePicData, editBannerData, changeSwitchValue, changeShortValue } from '../apis/pic'
import { getShareList } from '../apis/shareController'
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
interface option {
  id: number
  authName: string
}
interface Haibao {
  id: number
  title: string
}
let searchValue = ref('')
let tableData = ref([])
let currentPage = ref(1)
let dataTotal = ref(0)
let dialogFormVisible = ref(false)
let dialogState = ref('新增数据')
let editId = ref(0)
let dialogAuth = ref(false)
let authArr = ref([])
let authsOptions = ref<option[]>([])
let editDataUrl = ref('')
let fileList = ref([])
let haibaoList = ref<Haibao[]>([])

let form = reactive({
  title: '',
  name: '',
  target: 0,
  url: '',
  isShow: '1'
})
const ruleFormRef = ref<FormInstance>()
let rules = reactive({
  title: [
    { required: true, message: "名称必填", trigger: "blur" },
    { min: 2, max: 18, message: "名称长度2-18" }
  ],
  target: [{ required: true, message: "跳转地址必填", trigger: "blur" },]
})
const upload = ref<UploadInstance>()

const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}
const beforeRemove = (parmas) => {

}
const returnName = (id) => {
  let data = haibaoList.value.find(e => e.id == id)
  return data?.title
}
const uploadSuccess = (res) => {
  if (res.success != true) return
  form.url = res.url
  editDataUrl.value = ''
}
const switchChange = (row) => {
  let data = {
    id: row.id,
    show: row.isShow == '1' ? '1' : '2'
  }
  changeSwitchValue(data).then(res => {
    if (res.status == 200) {
      ElMessage({
        message: '修改数据成功',
        type: 'success',
      })
    }
  })
}
const cancelEdit = () => {
  editId.value = 0
  authArr.value = []
}
const handleChangeSort = async (row) => {
  let res = await changeShortValue({ id: row.id, short: row.short })
  if (res.status == 200) {
    ElMessage({
      message: '修改排序成功',
      type: 'success',
    })
  }
}
const resetForm = () => {
  let empty = {}
  for (let i in form) {
    empty[i] = ''
  }
  Object.assign(form, empty)
}
const searchClick = () => {
  currentPage.value = 1
  getData()
}
const addPicFn = () => {
  dialogState.value = '新增数据'
  fileList.value=[]
  let obg=document.querySelector('.el-upload-list')?.previousElementSibling
  if(obg){
    obg.innerHTML=''
  }
  dialogFormVisible.value = true
  form = reactive({
    title: '',
    name: '',
    target: 0,
    url: '',
    isShow: '1'
  })
}
const editData = (parmas) => {
  dialogState.value = "修改数据"
  editId.value = parmas.id
  dialogFormVisible.value = true
  editDataUrl.value = parmas.url.replace(/(\S*)\/banner\//, "")
  form = reactive({
    "name": parmas.name,
    "url": parmas.url,
    "target": parmas.target-0,
    "isShow": parmas.isShow,
    "title": parmas.title,
  })
}
const confirmEvent = async (row) => {
  let res = await deletePicData({ id: row.id })
  deletePic({ name: row.name })
  if (res.status == 200) {
    ElMessage({
      message: '删除图片成功',
      type: 'success',
    })
    getData()
  }
}
const handleCurrentChange = () => {
  getData()
}
const submitEdit = () => {

}
const cancel = (ruleFormRef) => {
  dialogFormVisible.value = false
  resetForm()
  fileList.value.length = 0
}
const submit = async (formEl) => {
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (dialogState.value == '新增数据') {
        let n = form.url ? form.url.replace(/(\S*)\/banner\//, "") : ''
        form.name = n
        let res = await addBannerData(form)
        if (res.status == 200) {
          ElMessage({
            message: '新增图片成功',
            type: 'success',
          })
          dialogFormVisible.value = false
          getData()
          resetForm()
          fileList.value.length = 0
        }
      } else {
        let data = {
          id: editId.value,
          ...form
        }
        let res = await editBannerData(data)
        if (res.status == 200) {
          ElMessage({
            message: '修改图片成功',
            type: 'success',
          })
          dialogFormVisible.value = false
          getData()
          resetForm()
          fileList.value.length = 0
        }
      }
      dialogState.value = "新增数据"
    } else {
      console.log(fields)
    }
  })
}
const getData = async () => {
  let parmas = {
    "title": searchValue.value.trim(),
    "page": currentPage.value,
  }
  let res = await getBannerPic(parmas)
  if (res.status == 200) {
    tableData.value = res.data.list
    dataTotal.value = res.data.total
  }
}
onBeforeMount(() => {
  getData()
  getShareList({ page: 1, pageSize: 9999 }).then(res => {
    if (res.status == 200) {
      haibaoList.value = res.data.list
    }
  })
})
</script>
<style lang="less" scoped>
.top-controllers {
  width: 100%;
  height: 30px;

  .w-50 {
    width: 200px;
    margin-right: 20px;
  }
}
</style>